//
//  RejectViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/11/24.
//  Copyright © 2015年 xingrong. All rights reserved.
//

#import "RejectViewController.h"
#import "AddRejectViewController.h"
#import "CustomSearchView.h"
#import "SocketRequest.h"
#import "RejectUser.h"
#import "NoviceView.h"
#import "Singleton.h"

@interface RejectViewController ()<SocketRequestDelegate,AddRejectViewControllerDelegate> {
    SocketRequest *_socketRequest;
    NSMutableArray *_rejectList;
    NSIndexPath *_selectedIndexPath;//判断是哪一个展开
    RejectUser *_currentRejectUser;
    
    BOOL _isSearch;
    NSMutableArray *_searchRejectList;
    NSIndexPath *_searchSelectedIndexPath;
}

@end

@implementation RejectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"拒收用户";
        _rejectList = [NSMutableArray arrayWithCapacity:1];
        _searchRejectList = [NSMutableArray arrayWithCapacity:1];
        _socketRequest = [[SocketRequest alloc] initWithSocketRequestDelegate:self];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _searchView.searchTextField.placeholder = @"请输入手机号查询";
    _searchView.searchTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _searchView.searchTextField.autocorrectionType = UITextAutocorrectionTypeNo;
    _searchView.isShowScanning = NO;
    [self reloadTableView];
    [self getRejectUserListSocket];
    BOOL isShowReject = [[[NSUserDefaults standardUserDefaults] objectForKey:FirstGuideReject] boolValue];
    if (!isShowReject) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:FirstGuideReject];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NoviceView *noviceView = [[NoviceView alloc] initWithType:NoviceTypeReject];
        [noviceView show];
    }
}

- (void)reloadTableView {
    if (_rejectList.count <= 0) {
        float height = [UIScreen mainScreen].bounds.size.height - 64;
        _searchView.hidden = YES;
        _footerView.hidden = YES;
        self.tableView.frame = CGRectMake(0, 0, 320, height);
        [self.tableView makeNoImageTip:@"当将用户手机号增加至拒收用户名单中，该用户的快件将不能投递到您的站点" Title:@"添加拒收用户" Target:self Selector:@selector(jumpAddRejectVC)];
        self.title = @"拒收用户";
    } else {
        [self.tableView makeNone];
        float height = [UIScreen mainScreen].bounds.size.height - 64 - 44 - 48;
        _searchView.hidden = NO;
        _footerView.hidden = NO;
        self.tableView.frame = CGRectMake(0, 44, 320, height);
        self.title = [NSString stringWithFormat:@"拒收用户(%d)",(int)_rejectList.count];
    }
    [Singleton shareInstance].statisticsCount.rejectUserCount = (int)_rejectList.count;
    [self.tableView reloadData];
}

- (void)getRejectUserListSocket {
    _selectedIndexPath = nil;
    if (_rejectList.count <= 0) {
        [self.tableView makeLoading];
    } else {
        [ToastActivity makeActivity:@"加载中..." InView:self.view];
    }
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STC2"]];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [_socketRequest addSocketData:mutableData SocketTag:1];
}

//取消黑名单socket
- (void)removeRejectUserSocket {
    [ToastActivity makeActivity:@"删除中..." InView:self.view];
    NSMutableData *mutableData = [[NSMutableData alloc] initWithData:[SocketMethod socketHeadDataMethod:@"STC1"]];
    [mutableData appendBytes:[@"0" UTF8String] length:1];
    [mutableData appendBytes:[SocketMethod checkLegal:[Singleton shareInstance].userMessage.websiteId] length:64];
    [mutableData appendBytes:[SocketMethod checkLegal:_currentRejectUser.telephone] length:16];
    NSData *remarkLengthData = [SocketMethod hexDataWithLength:0];
    [mutableData appendData:remarkLengthData];
    [_socketRequest addSocketData:mutableData SocketTag:2];
}

#pragma mark SocketRequestDelegate
- (void)socket:(GCDAsyncSocket *)socket Code:(NSString *)code Msg:(NSString *)msg Data:(NSData *)data {
    if (socket.socketTag == 1) {
        [self.tableView makeNone];
        [ToastActivity dismissInView:self.view];
        if ([code isEqualToString:SuccessSocket]) {
            [_rejectList removeAllObjects];
            NSString *content = [SocketMethod stringDecryHexData:data];
            DLog(@"拒收用户:%@",content);
            NSArray *array = [content componentsSeparatedByString:@"|"];
            for (NSString *string in array) {
                if (string.length > 0) {
                    RejectUser *reject = [[RejectUser alloc] initWithString:string];
                    [_rejectList addObject:reject];
                }
            }
            [self reloadTableView];
        } else {
            [self reloadTableView];
            if (_rejectList.count <= 0) {
                [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getRejectUserListSocket)];
            } else {
                [DSToast showText:msg InView:self.view];
            }
        }
    } else if (socket.socketTag == 2) {
        if ([code isEqualToString:SuccessSocket]) {
            if (_isSearch) {
                [_searchRejectList removeObject:_currentRejectUser];
            }
            [_rejectList removeObject:_currentRejectUser];
            [ToastActivity makeSuccess:@"删除成功" InView:self.view];
            [self reloadTableView];
        } else {
            [ToastActivity makeError:msg InView:self.view];
        }
    }
}

- (void)socket:(GCDAsyncSocket *)socket Msg:(NSString *)msg {
    if (socket.socketTag == 1) {
        [self.tableView makeNone];
        if (_rejectList.count <= 0) {
            [self.tableView makeTip:msg Title:@"重新加载" Target:self Selector:@selector(getRejectUserListSocket)];
        }
        [ToastActivity dismissInView:self.view];
        [DSToast showText:msg InView:self.view];
    } else if (socket.socketTag == 2) {
        [ToastActivity makeError:msg InView:self.view];
    }
}

#pragma makr CustomSearchViewDelegate
- (void)textEditingChanged:(NSString *)text {
    [_searchRejectList removeAllObjects];
    _searchSelectedIndexPath = nil;
    if (text.length > 0) {
        _isSearch = YES;
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.telephone contains %@",text];
        [_searchRejectList addObjectsFromArray:[_rejectList filteredArrayUsingPredicate:predicate]];
    } else {
        _isSearch = NO;
    }
    if (_searchRejectList.count <= 0 && _isSearch) {
        [self.tableView makeTip:@"查无结果，请重新搜索！"];
    } else {
        [self.tableView makeNone];
    }
    [self.tableView reloadData];
}

- (void)cancelSearch {
    _searchView.searchTextField.text = @"";
    _searchView.isShowCancel = NO;
    _isSearch = NO;
    [self.tableView makeNone];
    [self.tableView reloadData];
}

- (BOOL)customSearchLimitText:(NSString *)string {
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:TelephoneLimit] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    if (![string isEqualToString:filtered]) {
        return NO;
    }
    return YES;
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isSearch) {
        return _searchRejectList.count;
    }
    return _rejectList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    RejectUser *reject = nil;
    NSIndexPath *curtIndexPath = nil;
    if (_isSearch) {
        reject = [_searchRejectList objectAtIndex:indexPath.row];
        curtIndexPath = _searchSelectedIndexPath;
    } else {
        reject = [_rejectList objectAtIndex:indexPath.row];
        curtIndexPath = _selectedIndexPath;
    }
    if (curtIndexPath && [curtIndexPath compare:indexPath] == NSOrderedSame) {
        CGSize size = [reject.remark sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(296, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        return 44 + size.height + 12;
    }
    return 44.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"RejectCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, 120, 20)];
        label1.font = [UIFont systemFontOfSize:15];
        label1.textColor = MainTextColor;
        label1.tag = 10;
        [cell.contentView addSubview:label1];
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(158, 12, 150, 20)];
        label2.textAlignment = NSTextAlignmentRight;
        label2.font = [UIFont systemFontOfSize:13];
        label2.textColor = TipTextColor;
        label2.tag = 11;
        [cell.contentView addSubview:label2];
        UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(12, 44, 296, 15)];
        label3.font = [UIFont systemFontOfSize:13];
        label3.textColor = AssistTextColor;
        label3.tag = 12;
        label3.numberOfLines = 0;
        [cell.contentView addSubview:label3];
        UILabel *label4 = [[UILabel alloc] initWithFrame:CGRectMake(12, 43.5, 308, 0.5)];
        label4.tag = 13;
        label4.backgroundColor = LineColor;
        [cell.contentView addSubview:label4];
    }
    RejectUser *reject = nil;
    NSIndexPath *curtIndexPath = nil;
    if (_isSearch) {
        reject = [_searchRejectList objectAtIndex:indexPath.row];
        curtIndexPath = _searchSelectedIndexPath;
    } else {
        reject = [_rejectList objectAtIndex:indexPath.row];
        curtIndexPath = _selectedIndexPath;
    }
    UILabel *telephoneLabel = [cell viewWithTag:10];
    UILabel *timeLabel = [cell viewWithTag:11];
    UILabel *remarkLabel = [cell viewWithTag:12];
    UILabel *lineLabel = [cell viewWithTag:13];
    telephoneLabel.text = reject.telephone;
    timeLabel.text = reject.time;
    if (curtIndexPath && [curtIndexPath compare:indexPath] == NSOrderedSame) {
        remarkLabel.hidden = NO;
        CGSize size = [reject.remark sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(296, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        remarkLabel.frame = CGRectMake(remarkLabel.frame.origin.x, remarkLabel.frame.origin.y, remarkLabel.frame.size.width, size.height);
        remarkLabel.text = reject.remark;
        lineLabel.frame = CGRectMake(lineLabel.frame.origin.x, 44 + size.height + 12 - 0.5, lineLabel.frame.size.width, lineLabel.frame.size.height);
    } else {
        remarkLabel.hidden = YES;
        lineLabel.frame = CGRectMake(lineLabel.frame.origin.x, 43.5, lineLabel.frame.size.width, lineLabel.frame.size.height);
    }
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"取消拒收";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSearch) {
        if (_searchSelectedIndexPath == nil) {
            return YES;
        }
        return NO;
    }
    if (_selectedIndexPath == nil) {
        return YES;
    }
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    RejectUser *reject = nil;
    if (_isSearch) {
        reject = [_searchRejectList objectAtIndex:indexPath.row];
    } else {
        reject = [_rejectList objectAtIndex:indexPath.row];
    }
    _currentRejectUser = reject;
    [self removeRejectUserSocket];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_isSearch) {
        if (_searchSelectedIndexPath && [_searchSelectedIndexPath compare:indexPath] == NSOrderedSame) {
            _searchSelectedIndexPath = nil;
        } else {
            _searchSelectedIndexPath = indexPath;
        }
        [self.tableView reloadData];

    } else {
        if (_selectedIndexPath && [_selectedIndexPath compare:indexPath] == NSOrderedSame) {
            _selectedIndexPath = nil;
        } else {
            _selectedIndexPath = indexPath;
        }
        [self.tableView reloadData];
    }
}

#pragma mark UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_searchView.searchTextField resignFirstResponder];
}

#pragma mark AddRejectViewControllerDelegate
- (void)addRejectUserSuccess {
    [self getRejectUserListSocket];
}

#pragma mark NibAction
- (IBAction)addRejectUserAction:(id)sender {
    [self jumpAddRejectVC];
}

- (void)jumpAddRejectVC {
    AddRejectViewController *addRVC = [[AddRejectViewController alloc] initWithNibName:@"AddRejectViewController" bundle:nil];
    addRVC.delegate = self;
    [self.navigationController pushViewController:addRVC animated:YES];
}

@end
